<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="funcName">
        <el-input
          v-model="queryParams.funcName"
          placeholder="请输入功能名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="moduleName">
        <el-input
          v-model="queryParams.moduleName"
          placeholder="请输入模块名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="funcName">
        <el-input
          v-model="queryParams.funcName"
          placeholder="请输入功能名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="auditState">
        <el-select v-model="queryParams.auditState" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lcdp:codeModel:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleGenTable"
          v-hasPermi="['lcdp:codeModel:generate']"
          >生成
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="openImportTable"
          v-hasPermi="['lcdp:codeModel:import']"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lcdp:codeModel:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lcdp:codeModel:delete']"
          >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="success" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleAudit"-->
      <!--          v-hasPermi="['lcdp:codeModel:audit']">审核-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="success" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleUnaudit"-->
      <!--          v-hasPermi="['lcdp:codeModel:audit']">反审核-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="warning"-->
      <!--            plain-->
      <!--            icon="el-icon-download"-->
      <!--            size="mini"-->
      <!--            @click="handleExport"-->
      <!--            v-hasPermi="['lcdp:codeModel:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="模型名称" prop="modelName" />
      <el-table-column label="功能名称" align="center" prop="funcName" />
      <el-table-column label="模型类别" prop="modelType" width="80" />
      <el-table-column label="模块名称" prop="moduleName" width="80" />
      <el-table-column label="模板类型" align="center" prop="templateType" />
      <el-table-column label="审核状态" align="center" prop="auditState" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_audit_status" :value="scope.row.auditState" />
        </template>
      </el-table-column>
      <el-table-column label="开关状态" align="center" prop="switchState" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_switch_status" :value="scope.row.switchState" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
            v-hasPermi="['lcdp:codeModel:preview']"
            >预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="!canEdit(scope.row)"
            @click="handleEditTable(scope.row)"
            v-hasPermi="['lcdp:codeModel:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="!canDelete(scope.row)"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lcdp:codeModel:delete']"
            >删除
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-refresh"
            @click="handleSynchDb(scope.row)"
            v-hasPermi="['lcdp:codeModel:edit']"
            >同步
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-download"
            @click="handleGenTable(scope.row)"
            v-hasPermi="['lcdp:codeModel:generate']"
            >生成代码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.currentPage"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览界面 -->
    <el-dialog
      :title="preview.title"
      :visible.sync="preview.open"
      width="90%"
      top="5vh"
      append-to-body
      class="scrollbar"
    >
      <el-tabs v-model="preview.activeName" tab-position="left">
        <el-tab-pane v-for="(item, index) in preview.data" :label="item.fileName" :name="index" :key="index">
          <el-link
            :underline="false"
            icon="el-icon-document-copy"
            v-clipboard:copy="item.content"
            v-clipboard:success="clipboardSuccess"
            style="float: right"
            >复制
          </el-link>
          <pre><code class="hljs" v-html="highlightedCode(item.content, item.fileName)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 添加或修改代码模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="模型描述" prop="modelComment">
          <el-input v-model="form.modelComment" placeholder="请输入模型描述" />
        </el-form-item>
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="form.moduleName" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="功能名称" prop="funcName">
          <el-input v-model="form.funcName" placeholder="请输入功能名称" />
        </el-form-item>
        <el-form-item label="实体名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入实体名称" />
        </el-form-item>
        <el-form-item label="对象名称" prop="objectName">
          <el-input v-model="form.objectName" placeholder="请输入对象名称" />
        </el-form-item>
        <el-form-item label="生成包名" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入生成包名" />
        </el-form-item>
        <el-form-item label="子模型名" prop="subModelName">
          <el-input v-model="form.subModelName" placeholder="请输入子模型名" />
        </el-form-item>
        <el-form-item label="子表外键" prop="subModelFk">
          <el-input v-model="form.subModelFk" placeholder="请输入子表外键" />
        </el-form-item>
        <el-form-item label="代码作者" prop="codeAuthor">
          <el-input v-model="form.codeAuthor" placeholder="请输入代码作者" />
        </el-form-item>
        <el-form-item label="分页大小" prop="pagesize">
          <el-input v-model="form.pagesize" placeholder="请输入分页大小" />
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentMenu">
          <el-input v-model="form.parentMenu" placeholder="请输入上级菜单" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="menuIcon">
          <el-input v-model="form.menuIcon" placeholder="请输入菜单图标" />
        </el-form-item>
        <el-form-item label="菜单参数" prop="menuParams">
          <el-input v-model="form.menuParams" placeholder="请输入菜单参数" />
        </el-form-item>
        <el-form-item label="页面布局" prop="pageLayout">
          <el-input v-model="form.pageLayout" placeholder="请输入页面布局" />
        </el-form-item>
        <el-form-item label="工具栏" prop="toolbar">
          <el-input v-model="form.toolbar" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="操作栏" prop="actionBar">
          <el-input v-model="form.actionBar" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="其它生成选项" prop="options">
          <el-input v-model="form.options" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-table ref="import" @ok="handleQuery" />
  </div>
</template>

<script>
import {
  insert,
  deleteByIds,
  genCode,
  queryById,
  pageList,
  previewTable,
  synchDb,
  updateById,
} from '@/api/lcdp/codeModel';
import importTable from './importTable';
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/github-gist.css';
import { canDelete, canEdit } from '@/utils/permission';

hljs.registerLanguage('java', require('highlight.js/lib/languages/java'));
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('html', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('vue', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));
hljs.registerLanguage('typescript', require('highlight.js/lib/languages/typescript'));
hljs.registerLanguage('sql', require('highlight.js/lib/languages/sql'));
hljs.registerLanguage('properties', require('highlight.js/lib/languages/properties'));

export default {
  name: 'CodeModelDO',
  dicts: ['sys_delete_status', 'sys_audit_status'],
  components: { importTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        currentPage: 1,
        pageSize: 20,
        modelType: null,
        modelName: null,
        modelComment: null,
        moduleName: null,
        funcName: null,
        className: null,
        objectName: null,
        packageName: null,
        subModelName: null,
        subModelFk: null,
        codeAuthor: null,
        pagesize: null,
        parentMenu: null,
        menuIcon: null,
        menuParams: null,
        formType: null,
        pageLayout: null,
        templateType: null,
        toolbar: null,
        actionBar: null,
        options: null,
        auditState: null,
        editState: null,
        switchState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelType: [{ required: true, message: '模型类别不能为空', trigger: 'change' }],
        modelName: [{ required: true, message: '模型名称不能为空', trigger: 'blur' }],
        modelComment: [{ required: true, message: '模型描述不能为空', trigger: 'blur' }],
        moduleName: [{ required: true, message: '模块名称不能为空', trigger: 'blur' }],
        funcName: [{ required: true, message: '功能名称不能为空', trigger: 'blur' }],
        className: [{ required: true, message: '实体名称不能为空', trigger: 'blur' }],
        objectName: [{ required: true, message: '对象名称不能为空', trigger: 'blur' }],
        parentMenu: [{ required: true, message: '上级菜单不能为空', trigger: 'blur' }],
        auditState: [{ required: true, message: '审核状态不能为空', trigger: 'blur' }],
        deleted: [{ required: true, message: '删除状态不能为空', trigger: 'blur' }],
        editState: [{ required: true, message: '编辑状态不能为空', trigger: 'blur' }],
        switchState: [{ required: true, message: '开关状态不能为空', trigger: 'blur' }],
      },
      // 预览参数
      preview: {
        open: false,
        title: '代码预览',
        data: {},
        activeName: '0',
      },
    };
  },
  created() {
    this.getList();
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null && time != this.uniqueId) {
      this.uniqueId = time;
      this.queryParams.currentPage = Number(this.$route.query.currentPage);
      this.getList();
    }
  },
  methods: {
    canDelete,
    canEdit,
    /** 查询代码模型列表 */
    getList() {
      this.loading = true;
      pageList(this.queryParams).then((resultDTO) => {
        this.list = resultDTO.data?.list;
        this.total = resultDTO.data?.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        modelType: null,
        modelName: null,
        modelComment: null,
        moduleName: null,
        funcName: null,
        className: null,
        objectName: null,
        packageName: null,
        subModelName: null,
        subModelFk: null,
        codeAuthor: null,
        pagesize: null,
        parentMenu: null,
        menuIcon: null,
        menuParams: null,
        formType: null,
        pageLayout: null,
        templateType: null,
        toolbar: null,
        actionBar: null,
        options: null,
        auditState: 0,
        deleted: 0,
        editState: 0,
        switchState: 0,
        updateBy: null,
        updateTime: null,
        createBy: null,
        createTime: null,
        auditBy: null,
        auditTime: null,
        remark: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    /** 生成代码操作 */
    handleGenTable(row) {
      const ids = row.id || this.ids;
      if (ids == '') {
        this.$modal.msgError('请选择要生成的数据');
        return;
      }
      if (row.genType === '1') {
        genCode(row.id).then((resultDTO) => {
          this.$modal.msgSuccess('成功生成到自定义路径：' + row.genPath);
        });
      } else {
        this.$download.zip('/lcdp/codeModel/generate?ids=' + ids, 'yloo');
      }
    },
    /** 同步数据库操作 */
    handleSynchDb(row) {
      const id = row.id;
      const modelName = row.modelName;
      this.$modal
        .confirm('确认要强制同步"' + modelName + '"表结构吗？')
        .then(function () {
          return synchDb(id);
        })
        .then(() => {
          this.$modal.msgSuccess('同步成功');
        })
        .catch(() => {});
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 预览按钮 */
    handlePreview(row) {
      previewTable(row.id).then((resultDTO) => {
        this.preview.data = resultDTO.data?.list;
        this.preview.open = true;
        this.preview.activeName = 'entity.java';
      });
    },
    /** 高亮显示 */
    highlightedCode(code, key) {
      var language = key.substring(key.lastIndexOf('.') + 1);
      const resultDTO = hljs.highlight(language, code || '', true);
      return resultDTO.value || '&nbsp;';
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess('复制成功');
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.modelNames = selection.map((item) => item.modelName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加代码模型';
    },
    /** 修改按钮操作 */
    handleEditTable(row) {
      const id = row.id || this.ids[0];
      const modelName = row.modelName || this.modelNames[0];
      const params = { currentPage: this.queryParams.currentPage };
      console.log(id);
      this.$tab.openPage('修改[' + modelName + ']模型', '/lcdp/codeModel/edit/' + id, params);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      queryById(id).then((resultDTO) => {
        this.form = resultDTO.data;
        this.open = true;
        this.title = '修改代码模型';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateById(this.form).then((resultDTO) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            insert(this.form).then((resultDTO) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除代码模型编号为"' + ids + '"的数据项？')
        .then(function () {
          return deleteByIds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
  },
};
</script>
